package com.lcxsoft.foodsservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lcxsoft.commonutils.JwtUtils;
import com.lcxsoft.commonutils.R;
import com.lcxsoft.feign.clients.OrderClient;
import com.lcxsoft.feign.query.OrderSaveQuery;
import com.lcxsoft.foodsservice.entity.Goods;
import com.lcxsoft.foodsservice.query.BuyFoodsQuery;
import com.lcxsoft.foodsservice.service.GoodsService;
import com.lcxsoft.foodsservice.url.FoodsServiceUrl;
import com.lcxsoft.userservice.entity.CustomUser;
import com.lcxsoft.userservice.service.CustomUserService;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lcx
 * @since 2022-01-20
 */
@RestController
@RequestMapping(FoodsServiceUrl.packageUrl)
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @Resource
    private CustomUserService customUserService;

    @Resource
    private OrderClient orderClient;


    /**
     * 首页查询商品信息列表
     * @param request
     * @return
     */
    @RequestMapping(value = FoodsServiceUrl.FoodsUrl.queryFoods, method = RequestMethod.POST)
    @ApiOperation("首页查询商品信息列表")
    public R queryFoods(HttpServletRequest request){
        Map<String, Integer> map = new HashMap<>();
        //获取用户主键
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        //判断是否登录
        if (StringUtils.isNullOrEmpty(userId)){
            return R.error().message("请先登录");
        }
        //获取用户所在寝室
        CustomUser customUser = customUserService.getOne(new LambdaQueryWrapper<CustomUser>().eq(CustomUser::getUserId, userId));
        //获取寝室下的零食列表
        List<Goods> list = goodsService.list(new LambdaQueryWrapper<Goods>().eq(Goods::getDormitoryId, customUser.getUserDormitory()));
        if (list.size() == 0){
            return R.error().message("请联系管理员补货");
        }
        return R.ok().data("foods", list);
    }

    /**
     * 购买商品
     * @param query
     * @param request
     * @return
     */
    @ApiOperation("购买商品")
    @RequestMapping(value = FoodsServiceUrl.FoodsUrl.buyFoods, method = RequestMethod.POST)
    @Transactional
    public R buyFoods(BuyFoodsQuery query, HttpServletRequest request){
        //1.获取用户余额信息
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        CustomUser customUser = customUserService.getOne(new LambdaQueryWrapper<CustomUser>().eq(CustomUser::getUserId, userId));
        BigDecimal userBalance = customUser.getUserBalance();
        //2.判断余额是否充足
        Goods goods = goodsService.getOne(new LambdaQueryWrapper<Goods>().eq(Goods::getGoodsId, query.getGoodsId()));

        BigDecimal speedBalance = BigDecimal.valueOf(goods.getGoodsPrice().doubleValue() * query.getChooseAmount());
        if (userBalance.compareTo(speedBalance) > 0 || userBalance.compareTo(speedBalance) == 0) {
            //3.检查库存
            if (goods.getGoodsNumber() - query.getChooseAmount() >= 0){
                //4.扣减库存
                goods.setGoodsNumber(goods.getGoodsNumber() - query.getChooseAmount());
                goodsService.updateById(goods);
                //5.扣减用户余额
                BigDecimal balance;
                balance = userBalance.subtract(speedBalance);
                customUser.setUserBalance(balance);
                customUserService.updateById(customUser);
                //6.生成订单
                OrderSaveQuery orderSaveQuery = new OrderSaveQuery();
                orderSaveQuery.setUserId(customUser.getUserId());
                orderSaveQuery.setGoodsId(goods.getGoodsId());
                orderSaveQuery.setOrdersAmount(query.getChooseAmount());
                orderSaveQuery.setOrdersPrice(goods.getGoodsPrice());
                orderSaveQuery.setOrdersTottle(speedBalance);
                //远程调用生成订单
                orderClient.createOrder(orderSaveQuery);
                return R.ok().message("购买成功，请取出物品");
            }
            return R.error().message("商品库存不足，请联系管理员补货");
        }else {
            return R.error().message("用户余额不足，请充值");
        }
    }

    /**
     * 根据ID查询商品实体
     * Feign使用
     * @param goodsId
     * @return
     */
    @ApiOperation("根据ID查询商品实体")
    @RequestMapping(value = FoodsServiceUrl.FoodsUrl.queryFoodsById, method = RequestMethod.POST)
    public Goods queryGoodsById(@RequestBody String goodsId){
        return goodsService.getOne(new LambdaQueryWrapper<Goods>().eq(Goods::getGoodsId, goodsId));
    }

    /**
     * 添加商品
     * 接口未联调
     * @param goods
     * @return
     */
    @ApiOperation("添加商品")
    @PostMapping(FoodsServiceUrl.FoodsUrl.addFoods)
    public R addFoods(@RequestBody Goods goods){
        return goodsService.saveOrUpdate(goods) ? R.ok().message("操作成功!") : R.error().message("操作失败!");
    }

    /**
     * 根据商品Id删除商品
     * 接口未联调
     * @param goodsId
     * @return
     */
    @ApiOperation("根据Id删除商品")
    @PostMapping(FoodsServiceUrl.FoodsUrl.deleteFoods)
    public R deleteFoods(String goodsId){
        return goodsService.removeById(goodsId) ? R.ok().message("操作成功!") : R.error().message("操作失败!");
    }



}

